#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import log
import json
from controls import data_card_img_mysql
from controls import data_img_base_mysql
from utils import fdfs
from utils import file_util
from utils.util import get_utf8_str

'''
仅供后台使用，批量更新城市卡牌展示图片数据
调用方式：参数1城市卡牌图片json文件名, 参数2所有卡牌图片存放的文件夹(图片名字为卡牌id加文件扩展名)
python import_cards_data.pyc city1_cards.json img_fold
'''
def import_cards(datafile, img_path):
    if not (img_path and datafile) :
        print 'please input city cards jsonfile and img_path'
    print 'datafile : %s' % datafile
    print 'img_path : %s' % img_path

    insert = 1 # insert operate
    update = 2 # update operate
    delete = 3 # delete operate
    print 'all op_type----------insert: %d, update: %d, delete: %d' % (insert, update, delete)

    # read all json file content
    jsonfile = open( datafile, 'r' )
    json_dict = {}
    try:
        all_the_text = jsonfile.read( )
        json_dict = json.loads(get_utf8_str(all_the_text))
    finally:
        jsonfile.close( )

    # data check
    if not json_dict :
        print 'jsonfile is empty.'
        sys.exit()
    if 'cityid' not in json_dict :
        print 'jsonfile content dont has cityid.'
        sys.exit()
    if not os.path.exists( img_path ) :
        print 'cards img_path dont existed : ' + img_path
        sys.exit()

    if not img_path.endswith('/') :
        img_path += '/'
    cityid = int( json_dict['cityid'] )
    del json_dict['cityid']

    for ( cardid, img_item ) in json_dict.items() :
        cardid = int(cardid)
        print "cardid:"+ str(cardid) +",imgs:"+str(img_item)

        '''jsonfile content:
        {
           "1" : { "imgname" : "1.png", "op_type" : 2 },
           "2" : { "imgname" : "2.png", "op_type" : 2 },
           "cityid" : 1
        }
        '''
        if not img_item :
            continue

        type = img_item['op_type']
        img_item['cardid'] = cardid

        data_card_img_mysql.create_card_img_table_if_not_exist(cityid)
        filepath = os.path.join( img_path, "" )
        if insert == type :
            print 'insert into card_img_%d, cardid=%d, filename=%s' % (cityid, cardid, img_item['imgname'])
            if not img_item['imgname'] :
                continue
            res = file_util.img_file_upload_by_filename_v2(filepath, img_item['imgname'])
            print res
            if res['ret'] == 0 and res['res']:
                img_item['imgid']=res['res']['imgid']
                data_card_img_mysql.add_card_img_item(cityid, img_item)

        if update == type :
            print 'update card_img_%d, cardid=%d, filename=%s' % (cityid, cardid, img_item['imgname'])
            if not img_item['imgname'] :
                continue

            res = file_util.img_file_upload_by_filename_v2(filepath, img_item['imgname'])
            print res
            if res['ret'] == 0 and res['res']:
                # get old card imgid
                old_img_dict = data_card_img_mysql.get_card_img_by_cardid( cityid, cardid )
                if not old_img_dict :
                    img_item['imgid']=res['res']['imgid']
                    data_card_img_mysql.add_card_img_item(cityid, img_item)
                    continue
                else :
                    # delete old img in fdfs
                    imgid = old_img_dict['imgid']
                    img_base_item = data_img_base_mysql.get_img_base_by_imgid( imgid )

                    if img_base_item :
                        p_group = str(img_base_item['group'])
                        file_id = img_base_item['path'] + '.'+ img_base_item['ext']
                        file_id_100 = img_base_item['path'] + '_100' + '.'+ img_base_item['ext']
                        file_id_300 = img_base_item['path'] + '_300' + '.'+ img_base_item['ext']

                        print 'group=%s, file_id=%s' % (p_group, file_id)
                        try :
                            fdfs.delete_file_by_group_file_id( p_group, file_id )
                            fdfs.delete_file_by_group_file_id( p_group, file_id_100 )
                            fdfs.delete_file_by_group_file_id( p_group, file_id_300 )
                        except Exception as e :
                            log.exp(e)
                        data_img_base_mysql.delete_img_base_by_imgid(imgid)

                    # update new img in card_img table
                    img_item['imgid']=res['res']['imgid']
                    data_card_img_mysql.update_card_img_item( cityid, img_item )
        if delete == type :
            print 'delete from card_img_%d, cardid=%d, filename=%s' % (cityid, cardid, img_item['imgname'])
            # delete old img in fdfs
            old_img_dict = data_card_img_mysql.get_card_img_by_cardid( cityid, cardid )
            if old_img_dict :
                # delete old img in fdfs
                imgid = old_img_dict['imgid']
                img_base_item = data_img_base_mysql.get_img_base_by_imgid( imgid )
                if not img_base_item :
                    continue

                p_group = str(img_base_item['group'])
                file_id = img_base_item['path'] + '.'+ img_base_item['ext']
                file_id_100 = img_base_item['path'] + '_100' + '.'+ img_base_item['ext']
                file_id_300 = img_base_item['path'] + '_300' + '.'+ img_base_item['ext']
                try :
                    fdfs.delete_file_by_group_file_id( p_group, file_id )
                    fdfs.delete_file_by_group_file_id( p_group, file_id_100 )
                    fdfs.delete_file_by_group_file_id( p_group, file_id_300 )
                except Exception as e :
                    log.exp(e)
                data_img_base_mysql.delete_img_base_by_imgid(imgid)

                # delete img in card_img table
                data_card_img_mysql.delete_card_img_item( cityid, img_item)

    return True

if __name__ == '__main__':
    datafile1 = sys.argv[1]
    img_path1 = sys.argv[2]
    import_cards(datafile1, img_path1)
    print 'OK'

